import { Constants } from './Constants';
import PageResult from './PageResult';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-10-06 15:45:35
 * @LastEditTime: 2024-11-14 17:26:41
 * @Description: 通用返回对象
 */
export class R<T> {
  public static SUCCESS: number = Constants.SUCCESS;

  /** 失败 */
  public static FAIL: number = Constants.FAIL;

  private code: number;

  private msg: string;

  private data: T;

  private rows: any[];

  private total: number;

  public static ok<U>(data?: U, msg?: string, code?: number): R<U> {
    if (!data) data = null;
    if (!code) code = R.SUCCESS;
    if (!msg) msg = '响应成功';
    return R.result(data, code, msg);
  }

  public static fail(msg?: string, code?: number) {
    if (!code) code = R.FAIL;
    if (!msg) msg = '响应成功';
    return R.result(null, code, msg);
  }

  public static page<U>(
    pageResult: PageResult<U>,
    msg?: string,
    code?: number,
  ): R<U> {
    if (!pageResult.rows) pageResult.rows = [];
    if (!pageResult.total) pageResult.total = 0;
    if (!code) code = R.SUCCESS;
    if (!msg) msg = '响应成功';
    return R.pegeResult(pageResult.rows, pageResult.total, code, msg);
  }

  private static result<U>(data: U, code: number, msg: string): R<U> {
    const apiResult: R<U> = new R<U>();
    apiResult.code = code;
    apiResult.data = data;
    apiResult.msg = msg;
    return apiResult;
  }

  private static pegeResult<U>(
    records: U[],
    total: number,
    code: number,
    msg: string,
  ): R<U> {
    const apiResult: R<U> = new R<U>();
    apiResult.code = code;
    apiResult.rows = records;
    apiResult.total = total;
    apiResult.msg = msg;
    return apiResult;
  }

  public isTrue(): boolean {
    return this.code == R.SUCCESS;
  }

  public static isSuccess(r: R<any>): boolean {
    return r.code == R.SUCCESS;
  }
}
